import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Article } from '@/modules/article/entities/article.entity';
import { Brackets, Repository } from 'typeorm';

@Injectable()
export class SearchService {
  constructor(
    @InjectRepository(Article)
    private articleRepository: Repository<Article>,
  ) {}

  async searchArticles(keyword: string, pageNo: number = 1, pageSize: number = 10) {
    const queryBuilder = this.articleRepository.createQueryBuilder('article');

    queryBuilder.where(new Brackets(qb => {
      qb.where("article.article_title LIKE :keyword", { keyword: `%${keyword}%` })
        .orWhere("article.article_content LIKE :keyword", { keyword: `%${keyword}%` });
    }));
    queryBuilder.leftJoinAndSelect('article.author', 'author');
    queryBuilder.leftJoinAndSelect('article.categories', 'categories');

    queryBuilder.skip((pageNo - 1) * pageSize);
    queryBuilder.take(pageSize);

    const [list, total] = await queryBuilder.getManyAndCount();

    return {
      list,
      total,
      pageNo,
      pageSize,
    };
  }
}
